package com.tjcd.project.library_base.base.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModelProvider;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.tjcd.project.library_base.base.model.BaseViewModel;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.reactivex.rxjava3.disposables.CompositeDisposable;

/**
 * @Author jiangKunKun
 * @CreateDate 2021/7/7
 * @Description
 * @SpittingGrooves
 */
public abstract class BaseActivity<V extends ViewDataBinding, VM extends BaseViewModel> extends AppCompatActivity  {
    /**
     * 数据控件绑定
     */
    protected V vBinding;
    /**
     * model层
     */
    protected VM vModel;

    /**
     * 当前上下文实例
     */
    protected Activity activity;
    /**
     * 页码
     */
    protected int pageNum = 1;
    /**
     * 每页长度 限制
     */
    protected int limit = 20;

    /**
     * rxjava3使用
     */
    protected CompositeDisposable mDisposables = new CompositeDisposable();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = this;
        logActivity();
        beforeSetContent();
        vBinding = DataBindingUtil.setContentView(this, attachLayoutRes());
        vModel = new ViewModelProvider(this).get(setViewModelClass());
        init();
    }

    /**
     * 设置viewode
     * @return
     */
    protected abstract Class<VM> setViewModelClass();

    /**
     * 初始化
     */
    protected abstract void init();

    /**
     * 绑定布局文件
     * @return 布局文件ID
     */
    protected abstract int attachLayoutRes();

    /**
     * setContent 之前的操作，可用于设置全屏等操作
     */
    protected void beforeSetContent() {

    }

    /**
     * 普通跳转
     * @param cls
     */
    public void goActivity(Class<?> cls) {
        startActivity(new Intent(activity, cls));
    }

    /**
     * Intent 传值跳转
     * 多参数
     * @param intent
     */
    public void goActivityIntent(Intent intent) {
        startActivity(intent);
    }

    /**
     * 单参数跳转
     * @param cls
     */
    public void goActivity(Class<?> cls, String key, Object value) {
        Intent intent = new Intent(activity, cls);
        setJumpParameters(intent, key, value);
        startActivity(intent);
    }

    /**
     * 多参数
     * @param cls
     * @param map map集合
     */
    public void goActivity(Class<?> cls, Map<String, Object> map) {
        Intent intent = new Intent(activity, cls);
        if (ObjectUtils.isNotEmpty(map)){
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String mapKey = entry.getKey();
                Object mapValue = entry.getValue();
                setJumpParameters(intent, mapKey, mapValue);
            }
        }
        startActivity(intent);
    }

    /**
     * 设置跳转改参数
     * @param intent
     * @param key
     * @param value
     */
    private void setJumpParameters(Intent intent, String key, Object value) {
        if (value instanceof String){
            intent.putExtra(key, (String) value);
        }else if (value instanceof Integer){
            intent.putExtra(key, (Integer) value);
        }else if (value instanceof Boolean){
            intent.putExtra(key, (boolean) value);
        }else if (value instanceof List){
            if (ObjectUtils.isNotEmpty(value)){
                if (((List<?>) value).get(0) instanceof String){
                    intent.putStringArrayListExtra(key, (ArrayList<String>) value);
                }else if (((List<?>) value).get(0) instanceof Integer){
                    intent.putIntegerArrayListExtra(key, (ArrayList<Integer>) value);
                }else if (((List<?>) value).get(0) instanceof Parcelable){
                    intent.putParcelableArrayListExtra(key, (ArrayList<? extends Parcelable>) value);
                }
            }
        }else if (value instanceof Parcelable){
            intent.putExtra(key, (Parcelable) value);
        }else if (value instanceof Serializable) {
            intent.putExtra(key, (Serializable) value);
        }
    }


    /**
     * 日志
     */
    protected void logActivity() {
        LogUtils.e("当activity是" + activity.getPackageName() + activity.getLocalClassName());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 接触绑定
        if (null != vBinding) {
            vBinding.unbind();
        }
    }

    /**
     * 点击屏幕赢藏软键盘
     * setClickHidekeyboard(((ViewGroup) findViewById(android.R.id.content)).getChildAt(0));
     * @param view
     */
    public void setClickHidekeyboard(View view) {
        // Set up touch listener for non-text box views to hide keyboard.
        if (!(view instanceof EditText)) {
            view.setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View v, MotionEvent event) {
                    hideSoftKeyboard(BaseActivity.this);
                    return false;
                }
            });
        }

        //If a layout container, iterate over children and seed recursion.
        if (view instanceof ViewGroup) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                View innerView = ((ViewGroup) view).getChildAt(i);
                setClickHidekeyboard(innerView);
            }
        }
    }

    /**
     * 隐藏软键盘
     * @param activity
     */
    public static void hideSoftKeyboard(Activity activity) {
        InputMethodManager inputMethodManager =
                (InputMethodManager) activity.getSystemService(
                        Activity.INPUT_METHOD_SERVICE);
        if (activity.getCurrentFocus() != null)
            inputMethodManager.hideSoftInputFromWindow(
                    activity.getCurrentFocus().getWindowToken(), 0);
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(newBase);
        overrideFontScale(newBase);
    }

    /**
     * 重置配置 fontScale：保持字体比例不变，始终为 1.
     */
    private void overrideFontScale(Context context) {
        if (context == null) return;
        Configuration configuration = context.getResources().getConfiguration();
        configuration.fontScale = 1f;
        applyOverrideConfiguration(configuration);
    }

}
